package com.huishao.demo.service.impl;

import com.huishao.demo.service.CheckService;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.huishao.demo.MyEnum.CheckStatus.*;

@Slf4j
@Service("CheckService")
public class CheckServiceImpl implements CheckService {

    @Autowired
    MinioClient minioClient;

    /**
     * 有问题的方法，慎用！需要参考minio的sdk
     * @return Map
     */
    @Override
    public Map<String,String> checkMinio() {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        Map<String, String> map = new HashMap<>();
        String nowDate = dateTimeFormatter.format(LocalDateTime.now());
        try {
            Iterable<Result<Item>> baseBackup = minioClient.listObjects(ListObjectsArgs.builder().bucket("base-backup").build());
            Iterable<Result<Item>> gitlabBackup = minioClient.listObjects(ListObjectsArgs.builder().bucket("gitlab-backup").build());
            StringBuffer sb = new StringBuffer();

            String baseBackupStatus = "";
            String bes95clusterStatus = "";
            String gitlabBackupStatus = "";

            for (Result<Item> result : baseBackup) {
                Item item = result.get();
                if ((nowDate).equals(item.lastModified().format(dateTimeFormatter))) {
                    baseBackupStatus = "ok";
                    break;
                }
            }
            if (!"ok".equals(baseBackupStatus)) {
                sb.append("baseBackup 备份有问题 ，请检查! -- \\n");
            }

            for (Result<Item> result : gitlabBackup) {
                Item item = result.get();
                if ((nowDate).equals(item.lastModified().format(dateTimeFormatter))) {
                    gitlabBackupStatus = "ok";
                    break;
                }
            }
            if (!"ok".equals(gitlabBackupStatus)) {
                sb.append("gitlabBackup 备份有问题 ，请检查! -- \\n");
            }
            sb.append("over");
            if ("over".equals(sb.toString())) {
                map.put("status", SUCCESS_STATUS.toString());
            }else {
                map.put("status", ERROR_STATUS.toString());
                map.put("errorMsg", sb.toString());
            }
            return map;
        } catch (Exception e) {
            log.error("查询minio服务时发生未知错误  " + e);
            map.put("status", SERVER_ERROR.toString());
            map.put("errorMsg", "查询minio服务时发生以下错误: " + e);
            return map;
        }

    }

    @Override
    public Map<String, String> deleteOverdueBackup() {
        return null;
    }
}
